package com.jubaozan.framework.sentinel.stat.traffic;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/7/28 9:39
 */

@Slf4j
public class TrafficInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<Long> START_TIME = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 记录请求实际发生时间（而非处理完成时间）
        START_TIME.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) {
        Long startTime = START_TIME.get();
        if (startTime == null) {
            return;
        }

        // 1. 计算RT（使用请求开始和结束时间）
        long endTime = System.currentTimeMillis();
        double rt = endTime - startTime;

        // 2. 资源名、IP、应用名获取（同之前）
        String resource = request.getRequestURI();
        String ip = "本地IP"; // 实际应从IpUtils获取
        String app = "应用名";

        // 3. 关键：传递请求实际发生时间（startTime）到缓存
        TrafficLogSecondCache.addTrafficLog(resource, app, ip, rt, ex == null, startTime);

        START_TIME.remove();
    }
}
